package com.supermarket.manage.business.member.controller;

import com.supermarket.manage.common.constant.ExportConstant;
import com.supermarket.manage.common.dto.CodeStatus;
import com.supermarket.manage.common.dto.PageBean;
import com.supermarket.manage.common.dto.ResponseResult;
import com.supermarket.manage.common.dto.member.request.MemberPageParams;
import com.supermarket.manage.common.pojo.Member;
import com.supermarket.manage.common.utils.POIUtil;
import com.supermarket.manage.common.utils.TimeUtil;
import com.supermarket.manage.common.validation.CheckGroup;
import com.supermarket.manage.provider.api.ucenter.MemberManageService;
import com.supermarket.manage.provider.api.ucenter.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Faxon
 * @version 1.0
 * @date 2020-03-12 19:37
 **/
@RestController
@RequestMapping("/member")
@Api(value = "MemberController", tags = "会员管理接口")
public class MemberController {

    @Reference(version = "1.0.0")
    private MemberManageService memberManageService;

    @Reference(version = "1.0.0")
    private UserService userService;

    @PreAuthorize("hasAuthority('/logined')")
    @PostMapping("/getMemberPageList")
    @ApiOperation(value = "条件、分页查询会员", notes = "必传参数：page，size，buyerId（其他为搜索条件）")
    public ResponseResult<PageBean<Member>> getMemberPageList(@Validated({CheckGroup.Page.class})
                                                              @RequestBody MemberPageParams params) {
        PageBean<Member> pageBean = memberManageService.getMemberPageList(params);
        return new ResponseResult<>(CodeStatus.OK, "查询成功", pageBean);
    }

    @PreAuthorize("hasAuthority('/logined')")
    @GetMapping("/export")
    @ApiOperation(value = "导出会员列表", notes = "必传参数：buyerId（搜索条件为页面已输入的搜索条件）")
    public void export(@Validated({CheckGroup.Get.class}) MemberPageParams params, HttpServletResponse response) throws IOException {
        List<Member> members = memberManageService.getMemberList(params);
        List<Map<String, Object>> maps = new ArrayList<>();
        members.forEach(d -> {
            Map<String, Object> map = new HashMap<>(4);
            map.put("mphone", d.getMphone());
            map.put("createdManName", d.getCreatedManName());
            map.put("integral", d.getIntegral());
            map.put("created", TimeUtil.formatDate(d.getCreated(), TimeUtil.TIME_FORMAT));
            maps.add(map);
        });
        String fileName = ExportConstant.MEMBER_SHEETNAME + TimeUtil.getNow("yyyyMMdd");
        SXSSFWorkbook export = POIUtil.export(fileName, maps, ExportConstant.MEMBER_HEADERSNAME, ExportConstant.MEMBER_KEYS);

        POIUtil.writeTo(fileName, export, response);
    }

    @PreAuthorize("hasAnyAuthority('/','/member/manage')")
    @PostMapping("/addMember")
    @ApiOperation(value = "添加会员", notes = "必传参数：mphone，createdMan（当前登录账户的userId），buyerId")
    public ResponseResult<Void> addMember(@Validated({CheckGroup.Add.class})
                                          @RequestBody Member member) {
        Integer count = memberManageService.getCountByMphone(member);
        if (count > 0) {
            return new ResponseResult<>(CodeStatus.FAIL, "添加失败，该手机号已是您超市的会员");
        }
        Boolean aBoolean = memberManageService.addMember(member);
        if (aBoolean) {
            return new ResponseResult<>(CodeStatus.OK, "添加成功");
        }
        return new ResponseResult<>(CodeStatus.FAIL, "添加失败");
    }

    @PreAuthorize("hasAnyAuthority('/','/member/manage')")
    @GetMapping("/deleteMember/{mid}")
    @ApiOperation(value = "删除会员", notes = "删除会员")
    public ResponseResult<Void> deleteMember(@NotBlank(message = "会员id不能为空")
                                             @PathVariable String mid) {
        Boolean aBoolean = memberManageService.deleteMember(mid);
        if (aBoolean) {
            return new ResponseResult<>(CodeStatus.OK, "删除成功");
        }
        return new ResponseResult<>(CodeStatus.FAIL, "删除失败");
    }
}
